package com.chenfan.process.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.chenfan.ccp.common.result.R;
import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.util.tool.UuidUtil;
import com.chenfan.notify.MessageClient;
import com.chenfan.notify.vo.MessageDetailVo;
import com.chenfan.notify.vo.MessagePlanVo;
import com.chenfan.process.dto.ApprovalMessageDefaultParamDTO;
import com.chenfan.process.entity.po.ApprovalPo;
import com.chenfan.process.entity.po.ApprovalTemplatePo;
import com.chenfan.process.entity.po.TemplateConfigPo;
import com.chenfan.process.enums.ApprovalMessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 消息中心辅助类
 * @author wulg
 * @date 2024/9/14
 */
@Slf4j
public class MessageCenterHelper {

    /**
     * 发送消息
     * @param template
     * @param templatePo
     * @param approvalPo
     * @param config
     * @param remark
     */
    public static void send(String template, ApprovalTemplatePo templatePo, ApprovalPo approvalPo, List<Long> userIds, TemplateConfigPo config, String remark) {
        ApprovalMessageDefaultParamDTO approvalMessageDefaultParamDTO = ApprovalMessageDefaultParamDTO.builder()
                .createName(approvalPo.getCreateName())
                .name(templatePo.getTitle())
                .businessId(Objects.nonNull(approvalPo.getBusinessId()) ? approvalPo.getBusinessId().toString() : null)
                .code(approvalPo.getBusinessCode())
                .url(Objects.nonNull(config) ? config.getMessageUrl() : "")
                ._remark(remark)
                .operatorName(TenantUtil.defaultCurrentUserName())
                .createTime(DateUtil.format(approvalPo.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN))
                .build();
        // 设置参数
        Map<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(approvalMessageDefaultParamDTO), Map.class);
        if (!StringUtils.isEmpty(approvalPo.getBusinessParam())) {
            Map<String, String> businessParam = JSONObject.parseObject(ToStringUtil.transfer(approvalPo.getBusinessParam()), Map.class);
            map.putAll(businessParam);
        }
        MessagePlanVo messagePlanVo = new MessagePlanVo();
        messagePlanVo.setMessageKey(UuidUtil.generateUuid());
        messagePlanVo.setTemplate(template);
//      messagePlanVo.setBelongSystem(templatePo.getBelongSystem());
        messagePlanVo.setTenantId(ObjectUtils.defaultIfNull(approvalPo.getTenantId(), TenantUtil.getTenantId()));
        messagePlanVo.setTitle(templatePo.getTitle());
        messagePlanVo.setJumpUrlType(Objects.nonNull(config) ? config.getJumpUrlType() : "page");
        List<MessageDetailVo> details = defaultList(userIds).stream().map(userId -> {
            MessageDetailVo messageDetailVo = new MessageDetailVo();
            messageDetailVo.setUserId(userId);
            // 设置参数
            messageDetailVo.setExternParams(map);
            return messageDetailVo;
        }).collect(Collectors.toList());
        messagePlanVo.setDetails(details);
        log.info("开始发送【{}】模板消息，内容：{}", template, JSONObject.toJSONString(messagePlanVo));
        R<String> sendMessage = ApplicationContextUtil.getContext().getBean(MessageClient.class).sendMessage(messagePlanVo);
        log.info("结束发送【{}】模板消息，内容：{}", template, JSONObject.toJSONString(sendMessage));
    }

    /**
     * 发送默认模板消息
     * @param approvalMessageTypeEnum
     * @param templatePo
     * @param approvalPo
     * @param config
     * @param remark
     */
    public static void sendDefault(ApprovalMessageTypeEnum approvalMessageTypeEnum, ApprovalTemplatePo templatePo, ApprovalPo approvalPo, List<Long> userIds, TemplateConfigPo config, String remark)  {
        if(ApprovalMessageTypeEnum.isMcn(templatePo.getBelongSystem())) {
            send(approvalMessageTypeEnum.getMcnCode(), templatePo, approvalPo, userIds, config, remark);
        } else {
            send(approvalMessageTypeEnum.getEopCode(), templatePo, approvalPo, userIds, config, remark);
        }
    }


    private static <T> List<T> defaultList(List<T> list) {
        if(Objects.isNull(list)) {
            return new ArrayList<>(0);
        }
        return list;
    }
}
